#!/usr/bin/env python3
# -*- coding:utf-8 -*-



import sys


class PostgresqlConf(object):
    def __init__(self, file):
        with open(file, 'r') as f:
            lines = f.readlines()

        self.keys = []      # guc的名字，空行或者注释的话，则是''
        self.vals = []      # 对应的整行的内容
        for line in lines:
            self.vals.append(line)
            if line.strip() == '' or line.strip().startswith('#'):
                self.keys.append('')
                continue
            name = line.split('=')[0].strip()
            self.keys.append(name)

    def __str__(self):
        return '\n'.join(self.vals)

    def deduplicate(self):
        name_index = {}
        for i, name in enumerate(self.keys):
            if name == '':
                continue
            if name_index.get(name) is None:
                name_index[name] = i
            else:
                pre_index = name_index[name]
                self.keys[pre_index] = ''
                self.vals[pre_index] = ''

        res_keys = []
        res_vals = []
        for i, name in enumerate(self.keys):
            if name == '':
                continue
            res_keys.append(name)
            res_vals.append(self.vals[i])
        self.keys = res_keys
        self.vals = res_vals

    def merge(self, another):
        self.deduplicate()
        another.deduplicate()
        for name in another.keys:
            another_val = another.vals[name]
            if name in self.keys:
                idx = self.keys.index(name)
                self.vals[idx] = another_val
            else:
                self.keys.append(name)
                self.vals.append(another_val)


def usage():
    print("""
1、dedup。 过滤postgresql.conf里的一些重复配置。得到去重结果。
    python3 postgresqlconf-operate.py dedup postgresql.conf1
    
2、merge。将postgresql.conf2的内容，合并更新到postgresql.conf1
    python3 postgresqlconf-operate.py merge postgresql.conf1 postgresql.conf2 
    """)
    

if __name__ == '__main__':
    if len(sys.argv) <= 1:
        usage()
        exit()
    if sys.argv[1] == 'dedup' and len(sys.argv) == 3:
        conf = PostgresqlConf(sys.argv[2])
        conf.deduplicate()
        print(conf)
    elif sys.argv[1] == 'merge' and len(sys.argv) == 4:
        conf1 = PostgresqlConf(sys.argv[2])
        conf2 = PostgresqlConf(sys.argv[3])
        conf1.merge(conf2)
        print(conf1)
    else:
        usage()


